package com.project.collectAPI.comm;

import com.project.collectAPI.comm.util.SignUtil;
import com.project.collectAPI.entity.MeiTuan.SystemParam;
import org.apache.commons.codec.digest.DigestUtils;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/*签名字典排序*/
public class MapKeySort {

    //给map集合中的key实现字典排序
    public static Map<String,Object> MapKeySort(Map<String,Object> map){
        Collection<String> keyset= map.keySet();
        List list=new ArrayList<String>(keyset);
        Collections.sort(list);
        //LinkedHashMap 有序不重复
        LinkedHashMap<String,Object> newMap = new LinkedHashMap<String,Object>();
        for (int i= 0;i< list.size(); i++) {
            System.out.println("循环:"+list.get(i).toString() + "=" + map.get(list.get(i).toString()));
            newMap.put(list.get(i).toString(),map.get(list.get(i).toString()));
        }
        //System.out.println("排序后=========");
        //System.out.println(newMap);
        return newMap;
    }


    /**
     * 获得k1=v1&k2=v2 字符串
     * @param map
     * @return
     */
    public static String getKeyAndValueStr(Map<String,Object> map,String reqUrl) throws Exception {
        String result = "";
        try {
            List<Map.Entry<String,Object>> infoIds = new ArrayList<>(map.entrySet());
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> item : infoIds) {
                if (item.getKey() != null && item.getKey() != "") {
                    String key = item.getKey();
                    String val = item.getValue().toString();
                    if (!(val == "" || val == null)) {
                        sb.append(key + "=" + val + "&");
                    }
                }
            }
            //追加密钥(追加时，前面不需要加&)
            SystemParam systemParam=new SystemParam();
            result = sb.toString().substring(0, sb.length() - 1)+systemParam.getAppSecret();
        } catch (Exception e) {
            return null;
        }
        String finalString=(!Objects.isNull(reqUrl))?reqUrl+"?"+URLDecoder.decode(result):URLDecoder.decode(result);
        System.out.println("待签名...:"+finalString.replace(" ","+"));
        //System.out.println("待签名...:："+ URLEncoder.encode(finalString,"UTF-8"));

        //String md5Str=DigestUtils.md5Hex(finalString);

        String md5Str= SignUtil.genSig(finalString.replace(" ","+"));

        System.out.println("【签名】："+md5Str);


        return md5Str;  //签名要使用小写
        //return DigestUtils.sha256Hex(finalString).toUpperCase();
        //return myRSA2sign.rsaSign(finalString).toUpperCase();
    }
}
